package pkg.commands;
import java.util.*;
public class LocalDistributor implements ICommandExecListener{

	private ArrayList<ICommandExecutor> executors;
	private ArrayList<ICommand> toExecute = new ArrayList<ICommand>();
	
	public LocalDistributor(){
		executors = new ArrayList<ICommandExecutor>();
	}

	public void execute(ICommand cmd)
	{
		synchronized(toExecute)
		{
	    	toExecute.add(cmd);
		}
	}
	
	public void updateCommands()
	{
		ArrayList<ICommand> cmdCopy = null;
			cmdCopy = new ArrayList<ICommand>(toExecute);
			toExecute.clear();
			//System.out.println(cmdCopy.size());
		
		while(!cmdCopy.isEmpty())
		{
			ICommand cmd = cmdCopy.get(0);
			cmdCopy.remove(0);
    	   for(ICommandExecutor exec : executors)
    		  exec.execute(cmd);
		}
	}
	
	public void register(ICommandExecutor exec)
	{
		executors.add(exec);
		exec.setListener(this);
	}
	
	@Override
	public void remove(ICommandExecutor exec) {
		executors.remove(exec);
	}
	

	@Override
	public void receive(ICommand cmd) {
		this.execute(cmd);
	}
}
